package app

import (
	"flag"
	"gitee.com/yysf-xin/dproxy/pkg/v2ray/clash"
	"github.com/mitchellh/go-homedir"
	"gopkg.in/yaml.v3"
	"io/fs"
	"io/ioutil"
	"os"
	"path"
)

type DbConfig struct {
	DbName   string `yaml:"db_name"`
	Upgrade  bool   `yaml:"-"`
	LogLevel int    `yaml:"log_level"`
}

type LogConfig struct {
	Router bool `yaml:"router"`
}

type Debug struct {
	Pprof bool
	Log   bool
}

type DirServer struct {
	Path string `yaml:"path"`
	Dir  string `yaml:"dir"`
}
type Server struct {
	Dir DirServer `yaml:"dir"`
}
type V2ray struct {
	Addr string `yaml:"addr"`
}

type V2rayArr []*V2ray

func (i *V2rayArr) Set(value string) error {
	*i = append(*i, &V2ray{
		Addr: value,
	})
	return nil
}
func (i *V2rayArr) String() string {
	return "v2fly listen addr http://user:pwd@ip:port"
}

type Ssl struct {
	Cert string `yaml:"cert"`
	Key  string `yaml:"key"`
}

type ConfigFile struct {
	Addr        string    `yaml:"addr"`
	EnableProxy bool      `yaml:"enable_proxy"`
	EnableWeb   bool      `yaml:"enable_web"`
	Db          DbConfig  `yaml:"db"`
	Log         LogConfig `yaml:"log"`
	Debug       Debug     `yaml:"debug"`
	Server      Server    `yaml:"server"`
	V2ray       V2rayArr  `yaml:"v2ray"`

	Ssl   Ssl              `yaml:"ssl"`
	Clash *clash.RootClash `yaml:"clash"`
}

type Config struct {
	File     ConfigFile
	FileName string
}

func readDefaultFile(dir, file string) string {
	f := path.Join(dir, file)
	_, err := os.Stat(f)
	if err == nil {
		return f
	} else {
		return file
	}
}

func NewConfigFile(c *Config) (cfg *ConfigFile, err error) {
	cfg = &c.File

	dir, _ := homedir.Dir()
	if dir != "" {
		dir = path.Join(dir, ".dproxy")
	}

	createFile := false
	if c.FileName == "" {
		c.FileName = readDefaultFile(dir, "dproxy.yml")
		createFile = false
	}
	if c.FileName != "" {
		var buf []byte
		_, err = os.Stat(c.FileName)
		if err == nil {
			if buf, err = ioutil.ReadFile(c.FileName); err == nil {
				err = yaml.Unmarshal(buf, cfg)
			}
		} else if createFile {
			if buf, err = yaml.Marshal(cfg); err == nil {
				err = ioutil.WriteFile(c.FileName, buf, fs.ModePerm)
			}
		} else {
			err = nil
		}
	}
	flag.Parse()

	if c.File.Db.DbName == "" {
		c.File.Db.DbName = readDefaultFile(dir, "dproxy.db")
	}

	return
}
func MaleDefault() *Config {
	return &Config{
		File: ConfigFile{
			Addr:        "127.0.0.1:1080",
			EnableProxy: true,
			EnableWeb:   true,
		},
		FileName: "dproxy.yml",
	}
}
